<template>
  <!-- 4.2 登录页初始模板 (原内容已覆盖) -->
  <!-- 7.1 登录页基础布局：  -->
  <!-- ① 登录页面的整体盒子 -->
  <div class="login-container">
    <!-- ② 登录的盒子 -->
    <div class="login-box">
      <!-- ③ 标题的盒子 -->
      <div class="title-box"></div>
      <!-- ④ 登录的表单区域 -->
      <!-- 7.2 表单验证 ↓ -->
      <el-form ref="loginForm" :model="form" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btn-reg" type="primary" @click="loginFn">登录</el-button>
          <el-link type="info" @click="$router.push('/register')">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getLogin } from '@/api/index'
import { mapMutations } from 'vuex' // 8.2
export default {
  name: 'my-login',
  data () {
    return {
      // 7.3 定义form对象
      form: {
        username: '',
        password: ''
      },
      // 7.4 定义规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: '用户名必须是 1-10 位的大小写字母数字',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是 6-15 位非空字符串',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['updateToken']),
    async loginFn () { // 到这,去到 router进行重定向默认打开的网页.
      // console.log('触发点击登录')

      // 7.7 点击[登录]，触发调用登录接口行为：(7.6步在api文件夹下)
      await this.$refs.loginForm.validate()
      const res = await getLogin(this.form)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 8.1 思路更改：去到store文件夹[index.js],将token存入vuex.
      // 8.2 将store的mutation函数"映射"过来 ↑
      this.updateToken(res.token)

      // 8.end (进行完 token持久化存储本地+存入vuex 之后,进行跳转主页面行为：)
      setTimeout(() => {
        this.$router.push('/home')
      }, 1500)
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url(@/assets/images/login_bg.jpg) center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 270px;
    padding: 0 30px;
    background-color: #fff;
    box-sizing: border-box;

    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .title-box {
      height: 60px;
      background: url(@/assets/images/login_title.png) no-repeat center;
    }

    .btn-reg {
      width: 100%;
    }
  }
}
</style>
